package com.parkinglot.WeChat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.parkinglot.core.WeChat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class WxQrCode {

    //获取AccessToken路径
    private static final String AccessToken_URL
            = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";//小程序id
    //获取二维码路径
    private static final String WxCode_URL
            = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN";//小程序密钥

    /**
     * 用于获取access_token
     *
     * @return access_token
     * @throws Exception
     */
    public static Map<String, Object> getAccessToken(String appid, String secret) throws Exception {
        String requestUrl = AccessToken_URL.replace("APPID", appid).replace("APPSECRET", secret);
        String a = "";
        Map<String, Object> map = new HashMap<String, Object>();
        URL u = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 设置不用缓存
        conn.setUseCaches(false);
        // 设置传递方式
        conn.setRequestMethod("GET");
        // 设置维持长连接
        conn.setRequestProperty("Connection", "Keep-Alive");
        //开始连接
        conn.connect();
        if (conn.getResponseCode() == 200) {
            System.out.println("连接成功");
            // 请求返回的数据
            InputStream in = conn.getInputStream();

            try {
                byte[] data1 = new byte[in.available()];
                in.read(data1);
                // 转成字符串
                a = new String(data1);
                map = (Map) JSON.parse(a);
                map.put("appId", WeChat.appid);
                map.put("status", "success");
                System.out.println(map);
                in.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return map;
    }


    /*
     * 获取 二维码图片
     *
     */
    public static void getminiqrQr(String accessToken, String uploadPath) {
//        String ctxPath = uploadPath;
//        String fileName = "twoCode.png";
//        String bizPath = "files";
//        String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
//        String ppath = ctxPath + File.separator + bizPath + File.separator + nowday;
//        File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
//        if (!file.exists()) {
//            file.mkdirs();// 创建文件根目录
//        }
//        String savePath = file.getPath() + File.separator + fileName;
//        String qrCode = bizPath + File.separator + nowday + File.separator + fileName;
////        if (ppath.contains("\\")) {
////            ppath = ppath.replace("\\", "/");
////        }
//        if (qrCode.contains("\\")) {
//            qrCode = qrCode.replace("\\", "/");
//        }
////        String codeUrl=ppath+"/twoCode.png";
//        System.out.print(qrCode);
//        System.out.print(savePath);
        try {
//            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken);
            String wxCodeURL = WxCode_URL.replace("ACCESS_TOKEN", accessToken);
            URL url = new URL(wxCodeURL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", "1234567890");
            paramJson.put("page", "/page/index/index");
            paramJson.put("width", 200);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //文件生成路径FIle
            FileOutputStream stream = new FileOutputStream(new File("E:\\demo\\img.png"));
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            System.out.println(br.readLine());


            byte[] arr = new byte[1024];
            int len;
            while ((len = inputStream.read(arr)) != -1) {
                stream.write(arr, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // return qrCode;
    }

    public static void main(String[] args) throws Exception {

        Map<String, Object> map = WxQrCode.getAccessToken("wx9832ac19576d1e1b", "fb83c553d05fd30d1a62c94c879596f4");
        String uploadpath = "D:/tcc";
        String acctoken = map.get("access_token").toString();
        WxQrCode.getminiqrQr(acctoken, uploadpath);
    }
}
